package com.sec.android.app.myfiles.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.DownloadManager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.info.AppConstants.DownloadHistoryType;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.util.SemFwWrapper;
import com.sec.android.app.myfiles.util.UiUtils;

import java.io.File;

public class ConfirmOmaDialog extends DialogFragment {

    public static final String ARG_OMA_ITEMS = "arg_omas";

    private DownloadManager mDownloadManager;
    // private ConfirmOmaViewHolder mViewHolder;

    private boolean mIsDialogShowing = false;
    private String mExistingPath = null;

    private static final String DM_ID = "dm_id";
    private static final String DM_PATH = "dm_file_path";
    private static final String DM_OLDPATH = "dm_file_oldPath";
    private static final String DM_NAME = "dm_file_name";
    private static final String DM_VENDOR = "dm_file_vendor";
    private static final String DM_SIZE = "dm_file_size";
    private static final String DM_VERSION = "dm_file_version";
    private static final String DM_MIMETYPE = "dm_file_mimetype";
    private static final String DM_DESCRIPTION = "dm_file_description";

    public TextView mName;
    public TextView mVendor;
    public TextView mSize;
    public TextView mVersion;
    public TextView mType;
    public TextView mDescription;

    public static Bundle sArgs = new Bundle();

    public static ConfirmOmaDialog getDialog(final long id, final String name, final String path, final String vendor,
                                             final long size, final long version, final String mimetype, final String description) {

        /**
         * Create a new instance of ConfirmOmaDialog, providing ARG_OMA_ITEMS as
         * argument.
         */

        ConfirmOmaDialog fg = new ConfirmOmaDialog();

        sArgs.putLong(DM_ID, id);
        sArgs.putString(DM_NAME, name);
        sArgs.putString(DM_PATH, path);
        //args.putString(DM_OLDPATH, oldPath);
        sArgs.putString(DM_VENDOR, vendor);
        sArgs.putLong(DM_SIZE, size);
        sArgs.putLong(DM_VERSION, version);
        sArgs.putString(DM_MIMETYPE, mimetype);
        sArgs.putString(DM_DESCRIPTION, description);

        fg.setArguments(sArgs);

        return fg;

    }

    public ConfirmOmaDialog() {
        super();
        mIsDialogShowing = true;
    }

    public boolean isDialogShowing() {
        return mIsDialogShowing;
    }

    public boolean isShowingSameDialog(String newPath) {
        return (mIsDialogShowing && ((mExistingPath != null) ? mExistingPath.equals(newPath) : false));
    }

    // Because of its in the dialog layout, so the parent view its empty
    @SuppressLint("InflateParams")
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final LayoutInflater inflater = getActivity().getLayoutInflater();
        final View view = inflater.inflate(R.layout.confirm_oma_layout, null);
        mDownloadManager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);

        AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.confirm_oma_title)).setView(view)
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Do nothing. Implementation is provided in the
                        // overriden handler.
                        // It's done this way, because I don't want to close the
                        // dialog
                        // immediately.
                    }
                }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // Do nothing. Implementation is provided in the
                        // overriden handler.
                        // It's done this way, because I don't want to close the
                        // dialog
                        // immediately.
                    }
                }).setOnKeyListener(new OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int key, KeyEvent event) {
                        // Consuming event - I don't want to allow to cancel the
                        // dialog
                        // with back button press.
                        return true;
                    }
                }).create();

        initViews(view);

        return dialog;
    }

    @Override
    public void onStart() {

        super.onStart();

        final AlertDialog dialog = (AlertDialog) getDialog();

        if (dialog != null) {

            // Overriding default click listeners, because I don't want to
            // control
            // when the dialog is being dismissed.
            dialog.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener(mPositiveClickListener);

            dialog.getButton(Dialog.BUTTON_NEGATIVE).setOnClickListener(mNegativeClickListener);

        }

    }

    /**
     * Shows dialog using commitAllowingStateLoss for committing
     * FragmentTransaction. The only danger is that state of the parent Fragment
     * might omit the fact, that the dialog has been shown.
     */
    public void showAllowingStateLoss(final FragmentManager fm, final String tag) {

        if (fm != null) {
            mExistingPath = getArguments().getString(DM_PATH);
            final FragmentTransaction t = fm.beginTransaction();
            t.add(this, tag);
            t.commitAllowingStateLoss();

        }

    }

    private boolean requestDownload() {

        Bundle data = getArguments();
        String path = data.getString(DM_PATH);
        String oldPath = data.getString(DM_OLDPATH);

        long id = data.getLong(DM_ID);
        long size = data.getLong(DM_SIZE);

        ContentValues values = new ContentValues();

        values.put("status", 183);
        values.put("current_bytes", 0);
        values.put("_data", path);

        if (size <= 0) {
            values.put("total_bytes", -1);
        } else {
            values.put("total_bytes", size);
        }
        values.putNull("_data");

        // name is "Rose-240x320.jpg
        // mData is "path" - /storage/emulated/0/Download/rose-240X320.dm
        // destfile - /storage/emulated/0/Download/rose-240X320.jpg
        // size - 45774
        // source - http://wap2.samsungmobile.com/weblogic
        values.put("hint", path);

        getActivity().getContentResolver().update(ContentUris.withAppendedId(Uri.parse("content://downloads/all_downloads"), id), values, null,
                null);
        deleteFileIfExists(oldPath);

        return false;

    }

    private void rejectCurrentItem() {

        Bundle data = getArguments();
        long id = data.getLong(DM_ID);
        String oldPath = data.getString(DM_OLDPATH);

        ContentValues values = new ContentValues();
        values.put("status", 490);
        getActivity().getContentResolver().update(ContentUris.withAppendedId(Uri.parse("content://downloads/all_downloads"), id), values, null,
                null);

        mDownloadManager.remove(id);
        deleteFileIfExists(oldPath);

    }

    private void deleteFileIfExists(String path) {
        try {
            if (!TextUtils.isEmpty(path)) {

                File file = SemFwWrapper.file(path);
                if (!file.delete()) {
                    Log.e(this, "deleteFileIfExists() : " + Log.getEncodedMsg(path) + " couldn't delete");
                }
            }

        } catch (Exception e) {
            Log.e(this, "Exception:" + e.toString());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIsDialogShowing = false;
        mExistingPath = null;
    }

    @Override
    public void dismissAllowingStateLoss() {
        try {
            super.dismissAllowingStateLoss();
        } catch (IllegalStateException e) {
            Log.e(this, "IllegalStateException:" + e.toString());
        } finally {
            mIsDialogShowing = false;
            mExistingPath = null;
        }
    }

    private OnClickListener mPositiveClickListener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            requestDownload();
            dismiss();
        }

    };

    private OnClickListener mNegativeClickListener = new OnClickListener() {

        @Override
        public void onClick(View view) {
            rejectCurrentItem();

            if (getTargetFragment() != null)
                getTargetFragment().onActivityResult(DownloadHistoryType.CANCEL, Activity.RESULT_CANCELED, null);

            dismiss();
        }

    };

    private void initViews(View view) {
        mName = (TextView) view.findViewById(R.id.confirm_oma_field_name);
        mVendor = (TextView) view.findViewById(R.id.confirm_oma_field_vendor);
        mSize = (TextView) view.findViewById(R.id.confirm_oma_field_size);
        mVersion = (TextView) view.findViewById(R.id.confirm_oma_field_version);
        mType = (TextView) view.findViewById(R.id.confirm_oma_field_type);
        mDescription = (TextView) view.findViewById(R.id.confirm_oma_field_description);

        Bundle data = getArguments();

        String sizeVal = UiUtils.makeFileSizeString(getActivity(), data.getLong(DM_SIZE));
        String version = Long.toString(data.getLong(DM_VERSION));

        mName.setText(data.getString(DM_NAME));
        mVendor.setText(data.getString(DM_VENDOR));
        mSize.setText(sizeVal);

        mVersion.setText(version);
        mType.setText(data.getString(DM_MIMETYPE));
        mDescription.setText(data.getString(DM_DESCRIPTION));
    }

    /**
     * Holds references to View items.
     */
    /*private static class ConfirmOmaViewHolder {
        public TextView mName;
        public TextView mVendor;
        public TextView mSize;
        public TextView mVersion;
        public TextView mType;
        public TextView mDescription;

        private Context mContext;

        public static ConfirmOmaViewHolder fromView(final Context context, final View view) {

            ConfirmOmaViewHolder d = new ConfirmOmaViewHolder();

            d.mContext = context;
            d.mName = (TextView)view.findViewById(R.id.confirm_oma_field_name);
            d.mVendor = (TextView)view.findViewById(R.id.confirm_oma_field_vendor);
            d.mSize = (TextView)view.findViewById(R.id.confirm_oma_field_size);
            d.mVersion = (TextView)view.findViewById(R.id.confirm_oma_field_version);
            d.mType = (TextView)view.findViewById(R.id.confirm_oma_field_type);
            d.mDescription = (TextView)view.findViewById(R.id.confirm_oma_field_description);

            return d;

        }

        public void updateForItem() {
            mName.setText(item.getName());
            mVendor.setText(item.getVendor());
            mSize.setText(Formatter.formatShortFileSize(mContext, item.getSize()));
            mVersion.setText(item.getVersion());
            mType.setText(item.getMimeType());
            mDescription.setText(item.getDescription());

        }

    }*/

}
